package com.mayikt.main.manage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mayikt.common.core.utils.RedisUtil;
import com.mayikt.main.api.impl.entity.SysUserLoginLog;
import com.mayikt.main.api.impl.mapper.SysUserLoginLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

/**
 * @author wangjin
 * @title: LoginLogManage
 * @projectName mayikt-cloud
 * @description: TODO
 * @date 2022/4/30 0030 16:30
 */
@Component
@Slf4j
@EnableAsync
public class LoginLogManage {
    @Autowired
    private SysUserLoginLogMapper SysUserLoginLogMapper;

    @Async("taskExecutor")
    public void asynLoginLog(SysUserLoginLog sysUserLoginLog) {
        //1,先根据userid 查询日志表，如果有登录记录
        //将原来登录日志的token从redis删除
        QueryWrapper<SysUserLoginLog> loginLogQueryWrapper = new QueryWrapper<>();
        loginLogQueryWrapper.eq("user_id", sysUserLoginLog.getUserId());
        loginLogQueryWrapper.eq("is_delete", 0);
        SysUserLoginLog dbUserLoginLog = SysUserLoginLogMapper.selectOne(loginLogQueryWrapper);
        String loginToken = null;
        if (dbUserLoginLog != null) {
            //获取上一次登录的token
            loginToken = dbUserLoginLog.getLoginToken();
            dbUserLoginLog.setIsDelete(1);
            SysUserLoginLogMapper.updateById(dbUserLoginLog);
            loginToken = dbUserLoginLog.getLoginToken();
        }
        //写入登录日志
        int resultCode = SysUserLoginLogMapper.insert(sysUserLoginLog);
        log.info("<resultCode>", resultCode);
        if (resultCode > 0 && !Strings.isEmpty(loginToken)) {
            //从redis移除
            RedisUtil.delKey(loginToken);
        }
        //调用接口异步发送短信

    }
}
